package com.fhz.day013jetpackall.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fhz.day013jetpackall.R;
import com.fhz.day013jetpackall.adapter.BannerAdapter;
import com.fhz.day013jetpackall.databinding.BannerFragmentBinding;
import com.fhz.day013jetpackall.entity.Banner;
import com.fhz.utilsfhz.ApiResponse;

import java.util.ArrayList;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class BannerFragment extends Fragment {

    private BannerViewModel mViewModel;

    public BannerFragmentBinding binding;
    public static BannerFragment newInstance() {
        return new BannerFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        //既可以创建无参的viewmodel.也可以创建有参的viewmodel
        mViewModel = new ViewModelProvider(this).get(BannerViewModel.class);

        binding = DataBindingUtil.inflate(inflater, R.layout.banner_fragment, container, false);


        binding.rv.setLayoutManager(new LinearLayoutManager(getActivity()));

        List<Banner> bannerList  = new ArrayList<>();
        BannerAdapter bannerAdapter = new BannerAdapter(bannerList);
        binding.rv.setAdapter(bannerAdapter);

        //更新数据源
        mViewModel.getBanner().observe(getActivity(), new Observer<ApiResponse<List<Banner>>>() {
            @Override
            public void onChanged(ApiResponse<List<Banner>> listApiResponse) {
                bannerList.clear();
                bannerList.addAll(listApiResponse.getData());
                bannerAdapter.notifyDataSetChanged();

                //room  entity dao database
                List<Banner> data = listApiResponse.getData();
                Banner[] banners = data.toArray(new Banner[data.size()]);
                //插入
                mViewModel.insertBanners(banners);

                //查询
                List<Banner> query = mViewModel.query();
                System.out.println(query.size());

                for (Banner banner : query) {
                    System.out.println(banner.toString());
                }

            }
        });

        return binding.getRoot();
    }



}